<template>
  <el-drawer
    v-model="open"
    title="课次详情"
    :with-header="true"
    size="90%"
    class="roll-call-drawer"
    :close-on-click-modal="false"
    :before-close="closeW"
  >
    <div style="font-size: 24px; margin-bottom: 30px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="12">
          {{ props.classTitle }}
        </el-col>
        <el-col
          :span="12"
          style="display: flex; flex-direction: row-reverse"
          v-if="props.isDetail"
        >
          <el-button
            type="primary"
            plain
            @click="handleEdit"
            style="margin: 0 20px"
            v-hasPermi="['registrar:class:adjust']"
          >
            编辑课次
          </el-button>
        </el-col>
      </el-row>
    </div>
    <el-space fill wrap direction="horizontal" style="width: 100%">
      <el-card shadow="never" header="课次信息">
        <el-form :model="form" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="上课时间">
                {{ form.classDate && form.classDate.slice(0, 10) + "   " }}
                {{ form.classStartTime + " ~ " + form.classEndTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授课课程">
                {{ form.courseNameC }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主班老师">
                {{ form.teacherName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="助教老师">
                {{ form.assistantName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授课课时">
                {{ form.classHour }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班级容量">
                {{
                  form.plannedStudentCount +
                  "(" +
                  (form.excess === 0 ? "可超额" : "不可超额") +
                  ")"
                }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上课教室">
                {{ form.classRoomName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上课内容">
                {{ form.description }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="点名时间">
                {{
                  form.callTime &&
                  form.callTime.slice(0, 10) +
                    "    " +
                    form.callTime.slice(11, 19)
                }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <el-card shadow="never">
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="学员名单" name="first" lazy>
            <el-row :gutter="10" class="mb8" v-if="props.isDetail">
              <el-col :span="12">
                <el-button
                  type="primary"
                  plain
                  @click="handleAddTemp"
                  v-hasPermi="['record:student:add']"
                >
                  添加临时学员
                </el-button>
                <el-button
                  type="primary"
                  plain
                  @click="handleAddMakeup"
                  v-hasPermi="['record:student:add']"
                >
                  添加补课学员
                </el-button>
              </el-col>
            </el-row>
            <el-alert
              title="【温馨提示】“添加临时学员”和“添加补课学员”均是实时操作，请谨慎处理；另上述操作将会引起学员列表的刷新，请在非修改状态下操作。"
              type="warning"
              :closable="false"
            />
            <el-table v-loading="loading" :data="memberList" border>
              <el-table-column
                label="学员姓名"
                align="center"
                prop="studentName"
              >
                <template #default="scope">
                  {{
                    scope.row.studentName +
                    (scope.row.temp === 0
                      ? "(临时学员)"
                      : scope.row.temp === 2
                      ? "(补课学员)"
                      : scope.row.temp === 3
                      ? "(试听学员)"
                      : "")
                  }}
                </template>
              </el-table-column>
              <el-table-column label="手机号" align="center" prop="mobile" />
              <el-table-column
                label="消耗方式"
                align="center"
                prop="courseName"
              />
              <el-table-column label="剩余额度" align="center" prop="num">
                <template #default="scope">{{
                  scope.row.num + "课时"
                }}</template>
              </el-table-column>
              <el-table-column
                label="到课状态"
                align="center"
                prop="state"
                width="300"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`memberList.${scope.$index}.state`"
                    v-if="scope.row.edit"
                  >
                    <el-button-group v-model="scope.row.state">
                      <el-button
                        :class="{ selected: scope.row.state === '2' }"
                        value="2"
                        @click="
                          scope.row.state = '2';
                          scope.row.classHourPay = form.classHour;
                          calculateNumList();
                        "
                        >到课</el-button
                      >
                      <el-button
                        :class="{ selected: scope.row.state === '3' }"
                        value="3"
                        @click="
                          scope.row.state = '3';
                          scope.row.classHourPay = form.classHour;
                          calculateNumList();
                        "
                        >迟到</el-button
                      >
                      <el-button
                        :class="{ selected: scope.row.state === '4' }"
                        value="4"
                        @click="
                          scope.row.state = '4';
                          scope.row.classHourPay = 0;
                          calculateNumList();
                        "
                        >请假</el-button
                      >
                      <el-button
                        :class="{ selected: scope.row.state === '5' }"
                        value="5"
                        @click="
                          scope.row.state = '5';
                          scope.row.classHourPay = 0;
                          calculateNumList();
                        "
                        >未到</el-button
                      >
                    </el-button-group>
                  </el-form-item>
                  <div v-else>
                    {{
                      {
                        "1": "未开课",
                        "2": "到课",
                        "3": "迟到",
                        "4": "请假",
                        "5": "未到",
                      }[scope.row.state]
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="补课状态"
                align="center"
                prop="repairState"
              >
                <template #default="scope">{{
                  {
                    0: "已补课",
                    1: "未补课",
                  }[scope.row.repairState]
                }}</template>
              </el-table-column>
              <!-- <el-table-column label="补课状态" align="center" prop="" /> -->
              <el-table-column
                label="扣除额度"
                align="center"
                prop="classHourPay"
                width="120"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`memberList.${scope.$index}.classHourPay`"
                    v-if="scope.row.edit"
                  >
                    <el-input
                      style="width: 60px"
                      v-model="scope.row.classHourPay"
                      @input="
                        (value) =>
                          (scope.row.classHourPay = Number(
                            value.replace(/[^\d]/g, '')
                          ))
                      "
                    ></el-input>
                    课时
                  </el-form-item>
                  <div v-else>
                    {{ scope.row.classHourPay + "课时" }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                align="center"
                prop="remark"
                width="260"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`memberList.${scope.$index}.remark`"
                    v-if="scope.row.edit"
                  >
                    <el-input
                      v-model="scope.row.remark"
                      type="textarea"
                      :rows="1"
                    ></el-input>
                  </el-form-item>
                  <div v-else>
                    {{ scope.row.remark }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="120"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="handleEditMember(scope.row)"
                    v-show="!scope.row.edit && scope.row.tstate === 0"
                    v-hasPermi="['registrar:class:adjust']"
                  >
                    修改
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    @click="handleUpdateMember(scope.row)"
                    v-show="scope.row.edit"
                    v-hasPermi="['registrar:class:adjust']"
                  >
                    保存
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    @click="handleCancelMember(scope.row)"
                    v-show="scope.row.edit"
                    v-hasPermi="['registrar:class:adjust']"
                  >
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="修改记录" name="second" lazy>
            <el-table v-loading="loading" :data="changeList" border>
              <el-table-column
                label="操作时间"
                align="center"
                prop="createDate"
                width="160"
              >
                <template #default="scope">
                  {{
                    scope.row.createDate &&
                    scope.row.createDate.slice(0, 10) +
                      "    " +
                      scope.row.createDate.slice(11, 19)
                  }}
                </template>
              </el-table-column>
              <el-table-column label="操作人" align="center" prop="name" />
              <el-table-column label="账号" align="center" prop="mobile" />
              <el-table-column label="操作类型" align="center" prop="type">
                <template #default="scope">
                  {{
                    {
                      "1": "修改学员到课信息",
                      "2": "添加临时学员",
                      "3": "添加补课学员",
                    }[scope.row.type]
                  }}
                </template>
              </el-table-column>
              <el-table-column
                label="修改内容"
                align="center"
                prop="description"
              />
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="changeQueryParams.pageNum"
              v-model:limit="changeQueryParams.pageSize"
              @pagination="getLog"
              size="small"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-space>
  </el-drawer>
  <Schedule
    title="编辑课次"
    btn="保存"
    v-bind="$props"
    ref="scheduleRef"
    @refreshPage="initPage"
    :refresh="true"
    from="rollCall"
  />
  <MemberSelector
    ref="mSelector"
    v-bind="$props"
    @refreshPage="handleAddTempMember"
    :data="form"
    title="添加临时学员"
    from="rollCall"
  />
  <MemberMakeupSelector
    ref="muSelector"
    v-bind="$props"
    :data="form"
    @refreshPage="handleAddMakeupMember"
  />
</template>

<script setup>
import { ElMessage } from "element-plus";
import Schedule from "./schedule.vue";
import MemberSelector from "./memberSelector.vue";
import MemberMakeupSelector from "./memberMakeupSelector.vue";
import {
  getRollCallDetailAPI,
  getMumberListByRollCallIdAPI,
  updateOrderByIdAPI,
  saveLogAPI,
  getLogAPI,
} from "@/api/registrar/class";
const props = defineProps({
  courseFilterIds: {
    type: String,
  },
  classId: {
    type: String,
  },
  classTitle: {
    type: String,
  },
  isVip: {
    type: String,
  },
  isDetail: {
    type: Boolean,
    default: true,
  },
});
const { proxy } = getCurrentInstance();
const emits = defineEmits(["refreshPage"]);

const loading = ref(false);
const scheduleRef = ref(null);
const open = ref(false);
const mSelector = ref(null);
const muSelector = ref(null);

const activeName = ref("first");

const data = reactive({
  form: {},
  currentItem: {},
  memberList: [],
  numList: [0, 0, 0, 0], // 到课、迟到、请假、未到的个数
  oldMemberList: [],
  changeList: [], // 修改记录
  changeQueryParams: {
    pageNum: 1,
    pageSize: 10,
  },
});

const {
  form,
  currentItem,
  numList,
  memberList,
  oldMemberList,
  changeList,
  changeQueryParams,
} = toRefs(data);

const total = ref(0);

const handleTabClick = async (tab, event) => {
  if (tab.paneName == "first") {
    getMumberListByLesson();
  } else {
    getLog();
  }
};

function getDetail() {
  getRollCallDetailAPI({ id: currentItem.value.id }).then((response) => {
    form.value = response.data;
  });
}

// 查询每节课次里的学员信息
function getMumberListByLesson() {
  getMumberListByRollCallIdAPI({
    orderNo: currentItem.value.orderNo,
    pageSize: 9999,
    pageNum: 1,
  }).then((response) => {
    memberList.value = response.rows;
    oldMemberList.value = JSON.parse(JSON.stringify(response.rows));
  });
}

function initPage() {
  getDetail();
  getMumberListByLesson();
}

// 编辑课次
function handleEdit() {
  scheduleRef.value.getScheduleDetailInRollCall(form.value.id);
}

// 某课次添加临时学员
function handleAddTemp() {
  mSelector.value.openSelector();
}

// 某课次添加补课学员
function handleAddMakeup() {
  muSelector.value.openSelector();
}

// 上课记录-点名记录-学员列表-修改
function handleEditMember(row) {
  row.edit = true;
  if (row.state === "1") {
    row.state = "2";
  }
}

// 获取修改记录
function getLog() {
  loading.value = true;
  getLogAPI({
    ...changeQueryParams.value,
    orderNo: currentItem.value.orderNo,
  }).then((response) => {
    loading.value = false;
    changeList.value = response.rows;
    total.value = response.total;
  });
}

async function handleAddTempMember(studentIdArr) {
  const param = {
    tid: form.value.id,
    studentIds: studentIdArr,
    type: 2,
  };
  await saveLog(param);
  getMumberListByLesson();
}

async function handleAddMakeupMember(studentIdArr) {
  const param = {
    tid: form.value.id,
    studentIds: studentIdArr,
    type: 3,
  };
  await saveLog(param);
  getMumberListByLesson();
}

// 保存修改记录
async function saveLog(param, row) {
  loading.value = true;
  saveLogAPI(param).then(() => {
    loading.value = false;
    if (row) row.edit = false;
  });
}

function ifChanged(a, b) {
  const { state, classHourPay, remark } = a;
  if (
    state === b.state &&
    classHourPay === b.classHourPay &&
    (remark === b.remark || (remark === null && b.remark === ""))
  )
    return false;
  else return true;
}

// 保存修改
async function handleUpdateMember(row) {
  // 比较下是否有更改
  const item = oldMemberList.value.filter((member) => {
    return member.id === row.id;
  })[0];
  const change = ifChanged(item, row);
  if (!change) {
    ElMessage({
      message: "信息无变化",
      type: "warning",
    });
    row.edit = false;
    return;
  } else {
    const { id, state, classHourPay, remark } = row;
    loading.value = true;
    await updateOrderByIdAPI({
      id,
      state,
      classHourPay,
      remark,
    })
      .then(() => {
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });

    const param = {
      tid: id,
      state,
      classHourPay,
      remark,
      type: 1,
    };
    await saveLog(param, row);
    getMumberListByLesson();
  }
}

// 取消修改
function handleCancelMember(row) {
  getMumberListByLesson();
  row.edit = false;
}

function calculateNumList() {
  numList.value = [0, 0, 0, 0];
  memberList.value.forEach((element) => {
    if (element.state === "2") {
      numList.value[0]++;
    } else if (element.state === "3") {
      numList.value[1]++;
    } else if (element.state === "4") {
      numList.value[2]++;
    } else if (element.state === "5") {
      numList.value[3]++;
    }
  });
}

function getRollCallDetail(item) {
  open.value = true;
  currentItem.value = item;
  initPage();
}

function closeW() {
  open.value = false;
  refreshParent();
}

function refreshParent() {
  emits("refreshPage");
}

defineExpose({ getRollCallDetail }); // 用于父组件调用
</script>

<style lang="scss" scoped>
.selected {
  background-color: rgb(235, 245, 255); /* 设置选中时的背景色 */
  color: rgb(64, 158, 255); /* 设置选中时的文字颜色 */
  border-color: rgb(159, 206, 255);
}
.num-style {
  color: #666;
  font-size: 14px;
  display: inline-block;
  margin-right: 20px;
}
</style>

<style scoped lang="scss">
.el-table__row .el-form-item {
  margin: 0;
}
</style>
